import logging
from typing import Dict, Any
from fastapi import Depends, APIRouter, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, Field
from dao.redis_dao.token_dao import get_depart_authority
from service.health_service import find_health_log, get_exception_count

logger = logging.getLogger(__name__)


class HealthLogRequest(BaseModel):
    """健康日志查询请求模型"""
    imei: list = Field(..., description="设备IMEI列表")
    startDate: str = Field(..., description="开始日期")
    endDate: str = Field(..., description="结束日期")
    type: str = Field(default="", description="数据类型")
    size: int = Field(default=1000, ge=1, le=10000, description="查询大小")


class ExceptionCountRequest(BaseModel):
    """异常统计请求模型"""
    startDate: str = Field(..., description="开始日期")
    endDate: str = Field(..., description="结束日期")
    level: int = Field(default=1, ge=1, le=3, description="异常等级")
    agg_list: list = Field(..., description="聚合字段列表")
    agg_size: int = Field(default=1000, ge=1, le=10000, description="聚合大小")


class StandardResponse(BaseModel):
    """标准响应模型"""
    code: int = Field(default=200)
    success: bool = Field(default=True)
    message: str = Field(default="操作成功")
    data: Any = Field(default=None)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
health_router = APIRouter(prefix='/test/wristband', tags=['手环', '健康数据'])


@health_router.post("/health_log", response_model=StandardResponse)
async def get_health_log(request: HealthLogRequest) -> StandardResponse:
    """
    获取健康日志数据
    """
    try:
        # 将Pydantic模型转换为字典
        data = request.dict()
        result = await find_health_log(data)
        
        logger.info(f"健康日志查询成功，返回{len(result)}条记录")
        return StandardResponse(
            data={
                "result": result,
                "total": len(result),
                "query_params": data
            }
        )
    except Exception as e:
        logger.error(f"健康日志查询失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询健康日志失败: {str(e)}"
        )


@health_router.post("/exception_count", response_model=StandardResponse)
async def get_health_exception_count(
    request: ExceptionCountRequest, 
    token: str = Depends(oauth2_scheme)
) -> StandardResponse:
    """
    获取健康异常统计数据
    """
    try:
        # 验证权限
        depart = await get_depart_authority(token)
        if not depart:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的访问令牌或权限不足"
            )
        
        # 执行查询
        data = request.dict()
        result = await get_exception_count(data, depart)
        
        logger.info(f"健康异常统计查询成功，部门: {depart}")
        return StandardResponse(
            data={
                "result": result,
                "department": depart,
                "query_params": data
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"健康异常统计查询失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询健康异常统计失败: {str(e)}"
        )